package chapter5_基础构建模块.Executor;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;

/**
 * 下载图片，并进行渲染
 */
public class Renderer {
    private final ExecutorService executor;

    public Renderer(ExecutorService executor) {
        this.executor = executor;
    }

    public void renderPage(CharSequence source) {
        List<ImageInfo> info = scanForImageInfo(source);
        ExecutorCompletionService<ImageData> completionService = new ExecutorCompletionService<>(executor);
        for (final ImageInfo imageInfo : info) {
            //提交任务
            completionService.submit(new Callable<ImageData>() {
                @Override
                public ImageData call() throws Exception {
                    return imageInfo.downloadImage();
                }
            });
        }

//        renderText(source);
        try {
            for (int t = 0, n = info.size(); t < n; t++) {
                // 如果有任务执行完成会立即返回，否则会阻塞
                Future<ImageData> f = completionService.take();
                ImageData imageData = f.get();
//                renderImage(imageData);
            }
        } catch (InterruptedException e) {
            // 设置中断标志
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            throw launderThrowable(e);
        }
    }

    //搜索需要下载的图片,构造的假方法
    public List<ImageInfo> scanForImageInfo(CharSequence source) {
        return Collections.emptyList();
    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new IllegalStateException("Not unchecked", t);
        }
    }
}

class ImageData {

}

class ImageInfo {
    ImageData downloadImage() {
        return new ImageData();
    }
}
